package com.example.xiaoxueqixiangmu.Fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.xiaoxueqixiangmu.Adapters.OrderAdapter;
import com.example.xiaoxueqixiangmu.LoginActivity;
import com.example.xiaoxueqixiangmu.MyFragmentActivity;
import com.example.xiaoxueqixiangmu.R;
import com.example.xiaoxueqixiangmu.bean.Order;
import com.example.xiaoxueqixiangmu.bean.Train;
import com.example.xiaoxueqixiangmu.jiemian.OrderControlActivity;
import com.example.xiaoxueqixiangmu.jiemian.chepiaoyudingActivity;
import com.example.xiaoxueqixiangmu.utils.Constant;
import com.example.xiaoxueqixiangmu.utils.Md5Utils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OrderFragment extends Fragment {
    private ArrayList<Order> orde;
    private Button btn_daizhifu,btn_allzhifu;
    private TextView tv_zhifuYN,tv_price;
    private List<HashMap<String, Object>> dataList,dataList1,dataList2;

    private SimpleAdapter adapter;
    private ListView listView;
    Handler handler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case 1:
                    int result=msg.arg1;
                    if (result==1){
                       //全部订单
                        OrderAdapter trainAdapter = new OrderAdapter(getActivity(), R.layout.ticket_list_item,orde);
                        ListView train_list = getActivity().findViewById(R.id.listView);
                        train_list.setAdapter(trainAdapter);
                        trainAdapter.notifyDataSetChanged();

                        train_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            }
                        });
                    }else if(result==0){
                    Toast.makeText(getActivity(),"没有数据",Toast.LENGTH_SHORT).show();

                    }
                    break;

            }

        }
    };
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.activity_order, container, false);

    }

    @Override
    public void onStart() {
        super.onStart();

        btn_daizhifu=getView().findViewById(R.id.btn_daizhifu);
        btn_allzhifu=getView().findViewById(R.id.btn_allzhifu);
        tv_zhifuYN=getView().findViewById(R.id.zhifuYN);
        tv_price=getView().findViewById(R.id.price);


        new Thread(){
            @Override
            public void run() {
                Message msg = Message.obtain();

                //使用OKHttpClient连接网络
                OkHttpClient client = new OkHttpClient();
                RequestBody requestBody = new FormBody.Builder()
                        .add("fromStationName", "沈阳")
                        .add("toStationName", "上海")
                        .add("startTrainDate", "2021-9-2")
                        .add("trainNo","G108")
                        .build();
                //读取已经存储好的sessionId
                SharedPreferences preferences = getActivity().getSharedPreferences("userinfo", Context.MODE_PRIVATE);
                String value = preferences.getString("cookie", "");
                //  RequestBody body=RequestBody.create(MediaType.parse("application/x-www-form-urlencoded;charset=utf-8"),"fromStationName");
                Request request = new Request.Builder()
                        .url(Constant.Host + "/otn/OrderList")
                        .addHeader("Cookie", value)
                        .post(requestBody)
                        .build();
                Response response = null;
                try {
                    response = client.newCall(request).execute();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (response.isSuccessful()){
                    try {
                        String responseData = response.body().string();
                        Log.d("显示Order", "Order：" + responseData);
                        Gson gson = new GsonBuilder().create();
                        Order[] orders = gson.fromJson(responseData, Order[].class);

                        //打印返回来的列车数据
                        for (Order o: orders
                        ) {
                            Log.d("打印orders详细信息",o.toString());
                        }
                        orde= new ArrayList<Order>(Arrays.asList(orders));
                        msg.what = 1;
                        msg.obj = orders;
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
                handler.sendMessage(msg);

            }
        }.start();



//点击待支付按钮，会刷新列表只存在未支付的的订单信息
        btn_daizhifu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dataList1 = new ArrayList<HashMap<String, Object>>();
                for (HashMap<String,Object> map:dataList){
                    if (map.get("zhifuYN").equals("未支付")){
                        final HashMap<String,Object> map2;
                        map2 =new HashMap<>();
                        map2.put("checi",map.get("checi"));
                        map2.put("cheming", map.get("cheming"));
                        map2.put("riqi", map.get("riqi"));
                        map2.put("dizhi",map.get("dizhi"));
                        map2.put("zhifuYN", map.get("zhifuYN"));
                        map2.put("price", map.get("price"));
                        map2.put("image", R.drawable.forward_25);
                        dataList1.add(map2);
                    }

                }
                adapter = new SimpleAdapter(getActivity(), dataList1, R.layout.order_list_item_layout,
                        new String[]{"checi", "cheming", "riqi", "dizhi", "zhifuYN", "price", "image"}, new
                        int[]{R.id.tv_checi, R.id.tv_cheming, R.id.riqi, R.id.dizhi, R.id.zhifuYN, R.id.price, R.id.imageView});
                listView.setAdapter(adapter);
            }
        });


        //点击全部订单按钮，刷新所有的订单信息
        btn_allzhifu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dataList2= new ArrayList<HashMap<String, Object>>();
                for (HashMap<String,Object> map:dataList){
                        final HashMap<String,Object> map3;
                        map3 =new HashMap<>();
                        map3.put("checi",map.get("checi"));
                        map3.put("cheming", map.get("cheming"));
                        map3.put("riqi", map.get("riqi"));
                        map3.put("dizhi",map.get("dizhi"));
                        map3.put("zhifuYN", map.get("zhifuYN"));
                        map3.put("price", map.get("price"));
                        map3.put("image", R.drawable.forward_25);
                        dataList2.add(map3);

                }
                adapter = new SimpleAdapter(getActivity(), dataList2, R.layout.order_list_item_layout,
                        new String[]{"checi", "cheming", "riqi", "dizhi", "zhifuYN", "price", "image"}, new
                        int[]{R.id.tv_checi, R.id.tv_cheming, R.id.riqi, R.id.dizhi, R.id.zhifuYN, R.id.price, R.id.imageView});
                listView.setAdapter(adapter);
                listView = getView().findViewById(R.id.listView);

            }
        });





























        dataList = new ArrayList<HashMap<String, Object>>();
        HashMap<String, Object> map1,map2,map3,map4;
            map1 = new HashMap<String, Object>();
        map1.put("checi", "2014Yp");
        map1.put("cheming", "G108");
        map1.put("riqi", "2021-9-2");
        map1.put("dizhi", "沈阳->上海");
        map1.put("zhifuYN", "已支付");
        map1.put("price", "288");
        map1.put("image", R.drawable.forward_25);
        dataList.add(map1);

       map2 = new HashMap<String, Object>();
        map2.put("checi", "2014Yp");
        map2.put("cheming", "G108");
        map2.put("riqi", "2021-9-2");
        map2.put("dizhi", "沈阳->上海");
        map2.put("zhifuYN", "未支付");
        map2.put("price", "288");
        map2.put("image", R.drawable.forward_25);
        dataList.add(map2);

         map3 = new HashMap<String, Object>();
        map3.put("checi", "2021#B32");
        map3.put("cheming", "T297");
        map3.put("riqi", "2021-8-8");
        map3.put("dizhi", "成都->厦门");
        map3.put("zhifuYN", "已支付");
        map3.put("price", "400");
        map3.put("image", R.drawable.forward_25);
        dataList.add(map3);

        map4 = new HashMap<String, Object>();
        map4.put("checi", "2021#D08");
        map4.put("cheming", "D290");
        map4.put("riqi", "2021-9-9");
        map4.put("dizhi", "海南->合肥");
        map4.put("zhifuYN", "已支付");
        map4.put("price", "100");
        map4.put("image", R.drawable.forward_25);
        dataList.add(map4);



        /*Log.d("list",dataList.size()+"");*/

        adapter = new SimpleAdapter(getActivity(), dataList, R.layout.order_list_item_layout,
                new String[]{"checi", "cheming", "riqi", "dizhi", "zhifuYN", "price", "image"}, new
                int[]{R.id.tv_checi, R.id.tv_cheming, R.id.riqi, R.id.dizhi, R.id.zhifuYN, R.id.price, R.id.imageView});
        listView = getView().findViewById(R.id.listView);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position>=0) {
                    Intent intent=new Intent(getActivity(), OrderControlActivity.class);
                    intent.putExtra("list",(Serializable)dataList1);
                    startActivity(intent);

                }
            }
        });

    }


}
